package com.qujia.customer.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.domain.entity.SysEnterprise;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.DateUtils;
import com.qujia.common.utils.MathUtil;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.customer.domain.CustomerCardUseRecord;
import com.qujia.customer.domain.ElectronicCardRefundRecord;
import com.qujia.customer.domain.PayOrderCard;
import com.qujia.customer.enums.CardRecordType;
import com.qujia.customer.mapper.CustomerCardUseRecordMapper;
import com.qujia.customer.mapper.ElectronicCardRefundRecordMapper;
import com.qujia.customer.service.ICustomerCardUseRecordService;
import com.qujia.customer.service.ICustomerStationEnterprisedService;
import com.qujia.system.domain.SysAppUserInfoUser;
import com.qujia.system.domain.SysEnterpriseUser;
import com.qujia.system.domain.SysStationUser;
import com.qujia.system.domain.vo.SysEnterpriseAndStationVo;
import com.qujia.system.service.IAppUserInfoUserService;
import com.qujia.system.service.ISysEnterpriseUserService;
import com.qujia.system.service.ISysStationUserService;
import com.qujia.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户电子会员卡充值消费记录Service业务层处理
 *
 * @author qujia
 * @date 2021-05-18
 */
@Service
@Slf4j
public class CustomerCardUseRecordServiceImpl implements ICustomerCardUseRecordService
{
    @Autowired
    private CustomerCardUseRecordMapper customerCardUseRecordMapper;
    @Autowired
    private IAppUserInfoUserService appUserInfoUserService;
    @Autowired
    private ISysEnterpriseUserService enterpriseUserService;
    @Autowired
    private ISysStationUserService stationUserService;
    @Autowired
    private ICustomerStationEnterprisedService customerStationEnterprisedService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ElectronicCardRefundRecordMapper electronicCardRefundRecordMapper;




    /**
     * 查询客户电子会员卡充值消费记录
     *
     * @param id 客户电子会员卡充值消费记录ID
     * @return 客户电子会员卡充值消费记录
     */
    @Override
    public CustomerCardUseRecord selectCustomerCardUseRecordById(Long id)
    {
        return customerCardUseRecordMapper.selectCustomerCardUseRecordById(id);
    }

    @Override
    public CustomerCardUseRecord selectCustomerCardUseRecordByOrderNo(String orderNo) {
        return customerCardUseRecordMapper.selectCustomerCardUseRecordByOrderNo(orderNo);
    }

    /**
     * 查询客户电子会员卡充值消费记录列表
     *
     * @param customerCardUseRecord 客户电子会员卡充值消费记录
     * @return 客户电子会员卡充值消费记录
     */
    @Override
    public List<CustomerCardUseRecord> selectCustomerCardUseRecordList(CustomerCardUseRecord customerCardUseRecord)
    {
        return customerCardUseRecordMapper.selectCustomerCardUseRecordList(customerCardUseRecord);
    }

    /**
     * 新增客户电子会员卡充值消费记录
     *
     * @param customerCardUseRecord 客户电子会员卡充值消费记录
     * @return 结果
     */
    @Override
    public int insertCustomerCardUseRecord(CustomerCardUseRecord customerCardUseRecord)
    {
        customerCardUseRecord.setCreateTime(DateUtils.getNowDate());
        return customerCardUseRecordMapper.insertCustomerCardUseRecord(customerCardUseRecord);
    }

    /**
     * 修改客户电子会员卡充值消费记录
     *
     * @param customerCardUseRecord 客户电子会员卡充值消费记录
     * @return 结果
     */
    @Override
    public int updateCustomerCardUseRecord(CustomerCardUseRecord customerCardUseRecord)
    {
        return customerCardUseRecordMapper.updateCustomerCardUseRecord(customerCardUseRecord);
    }

    /**
     * 批量删除客户电子会员卡充值消费记录
     *
     * @param ids 需要删除的客户电子会员卡充值消费记录ID
     * @return 结果
     */
    @Override
    public int deleteCustomerCardUseRecordByIds(Long[] ids)
    {
        return customerCardUseRecordMapper.deleteCustomerCardUseRecordByIds(ids);
    }

    /**
     * 删除客户电子会员卡充值消费记录信息
     *
     * @param id 客户电子会员卡充值消费记录ID
     * @return 结果
     */
    @Override
    public int deleteCustomerCardUseRecordById(Long id)
    {
        return customerCardUseRecordMapper.deleteCustomerCardUseRecordById(id);
    }

    /*充值消费汇总
     */
    @Override
    public CustomerCardUseRecord listCZXFData(CustomerCardUseRecord customerCardUseRecord) {
        return customerCardUseRecordMapper.listCZXFData(customerCardUseRecord);
    }

    /***
     * 小程序查询充值合计金额
     * @param customerCardUseRecord
     * @return
     */
    public CustomerCardUseRecord appletCzSum(CustomerCardUseRecord customerCardUseRecord){
        return   customerCardUseRecordMapper.appletCzSum(customerCardUseRecord);
    }


    /*充值消费汇总（包括已经退款的）
     */
    @Override
    public CustomerCardUseRecord listAllCZXFData(CustomerCardUseRecord customerCardUseRecord) {
        return customerCardUseRecordMapper.listAllCZXFData(customerCardUseRecord);
    }

    /***
     * 充值合计(包括退款)
     * @param params
     * @return
     */
    @Override
    public BigDecimal getTotalAmtByConditions(Map<String, Object> params) {
        return customerCardUseRecordMapper.getTotalAmtByConditions(params);
    }

    @Override
    public BigDecimal getTotalPresentAmtByConditions(Map<String, Object> params) {
        return customerCardUseRecordMapper.getTotalPresentAmtByConditions(params);
    }

    @Override
    public int insertBatch(List<CustomerCardUseRecord> recordList) {
        return customerCardUseRecordMapper.insertBatch(recordList);
    }

    @Override
    public List<CustomerCardUseRecord> selectCustomerCardUseRecordListWithNullValue(CustomerCardUseRecord customerCardUseRecord){
        return customerCardUseRecordMapper.selectCustomerCardUseRecordListWithNullValue(customerCardUseRecord);
    }

    @Override
    public List<CustomerCardUseRecord> selectCardUseRecordVoList(CustomerCardUseRecord form) {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        if(StringUtils.equals(UserConstants.LEVEL_TWO,sysUser.getUserLevel())){
            //油企
            form.setEnterpriseId(sysUser.getEnterpriseId());
            form.setCardUseRangeFlag(null);
        }else if(StringUtils.equals(UserConstants.LEVEL_THREE,sysUser.getUserLevel())){
            //油站
            form.setStationId(MathUtil.toInt(sysUser.getStationId()));
            form.setEnterpriseId(null);
            form.setCardUseRangeFlag(null);
        }else if (SecurityUtils.isPartner()) {
            SysEnterpriseAndStationVo itemIds = stationUserService.getItemIds(sysUser);
            if (itemIds != null){
                if(CollectionUtils.isEmpty(itemIds.getEnterpriseIds()) && CollectionUtils.isEmpty(itemIds.getStationIdsStr())){
                    return new ArrayList<>();
                }
                form.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());
                form.setStationIdList(itemIds.getStationIdsStr());
            } else {
                throw new CustomException(UserConstants.NO_ENTERPRISE);
            }
        }

//        if (form.getEnterpriseId() ==null && !StringUtils.equals("admin", current.getUsername()) && form.getStationId() == null) {
//            form.setEnterpriseId(current.getUser().getEnterpriseId());
//            SysStationUser sysStationUser=new SysStationUser();
//            sysStationUser.setEnterpriseId(current.getUser().getEnterpriseId());
//            List<SysStationUser> list=stationUserService.selectSysStationUserList(sysStationUser);
//            List<String> list1=new ArrayList<>();
//            if(list!=null && list.size()>0){
//                for(SysStationUser s:list) {
//                    list1.add(String.valueOf(s.getStationId()));
//                }
//                form.setStationIdList(list1);
//            }
//        }

        form.setStatus("1");
        // 交易类型payType 多选 按照 , 分割
        List<String> payTypeList = new ArrayList<>();
        String payType = null;
        if(StringUtils.isNotEmpty(form.getPayType())){
            String[] split = form.getPayType().split(",");
            for(String string : split){
                if("dzk".equals(string)){
                    payType = "dzk";
                }else {
                    payTypeList.add(string);
                }
            }
        }
        form.setPayTypeList(payTypeList);
        form.setPayType(payType); // 兼容交易类型为电子卡类型时，数据库字段为空 单独判断
        log.info("payTypeList:[{}]，payType: [{}]", JSONObject.toJSONString(payTypeList),payType);
        List<CustomerCardUseRecord> recordList = customerCardUseRecordMapper.selectCustomerCardUseRecordListWithNullValue(form);
        Map<Long,SysEnterprise> enterpriseMap = new HashMap<>();
        Map<Integer,SysEnterprise> staEnterMap = new HashMap<>();
        Map<String,SysAppUserInfoUser> userMap = new HashMap<>();
        Map<Integer,SysUser> sysUserMap = new HashMap<>();
        for(CustomerCardUseRecord customerCardUseRecord1:recordList){
            Integer stationId = customerCardUseRecord1.getStationId();
            Long enterpriseId = customerCardUseRecord1.getEnterpriseId();
            Integer operator = customerCardUseRecord1.getOperator();

            SysEnterprise sysEnterprise = null;
            if (enterpriseId != null) {
                sysEnterprise = enterpriseMap.get(enterpriseId);
            }
            if (sysEnterprise == null && stationId != null) {
                sysEnterprise = staEnterMap.get(stationId);
            }
            if(sysEnterprise == null){
                if(enterpriseId != null){
                    SysEnterpriseUser enterprise = enterpriseUserService.selectSysEnterpriseUserById(enterpriseId);
                    if (enterprise != null) {
                        sysEnterprise = new SysEnterprise();
                        sysEnterprise.setEnterpriseId(enterpriseId);
                        sysEnterprise.setEnterpriseName(enterprise.getEnterpriseName());
                        sysEnterprise.setCardUseRangeFlag(enterprise.getCardUseRangeFlag());
                        enterpriseMap.put(enterpriseId,sysEnterprise);
                    }
                }else{
                    sysEnterprise = customerStationEnterprisedService.getEnterpriseByStationId(stationId);
                    if (sysEnterprise != null) {
                        staEnterMap.put(stationId,sysEnterprise);
                    }
                }
            }
            if (sysEnterprise != null) {
                customerCardUseRecord1.setEnterpriseId(sysEnterprise.getEnterpriseId());
                customerCardUseRecord1.setEnterpriseName(sysEnterprise.getEnterpriseName());
                customerCardUseRecord1.setCardUseRangeFlag(sysEnterprise.getCardUseRangeFlag());
            }
            if (StringUtils.isBlank(customerCardUseRecord1.getCustomerName()) && customerCardUseRecord1.getEnterpriseId() != null) {
                String k = String.format("%d%s",customerCardUseRecord1.getEnterpriseId(),customerCardUseRecord1.getMobilePhone());
                SysAppUserInfoUser user = userMap.get(k);
                if (user == null) {
                    SysAppUserInfoUser userForm = new SysAppUserInfoUser();
                    userForm.setMobilePhone(customerCardUseRecord1.getMobilePhone());
                    userForm.setStationId(customerCardUseRecord1.getEnterpriseId());
                    user = appUserInfoUserService.getOne(userForm);
                    if (user != null) {
                        userMap.put(k,user);
                    }
                }
                if (user != null) {
                    customerCardUseRecord1.setCustomerName(user.getBlogNickName());
                    customerCardUseRecord1.setMemberCode(user.getMemberCode());
                }
            }

            String payType1 = customerCardUseRecord1.getPayType();
            if (StringUtils.isBlank(payType1)) {
                // 电子卡支付，查询订单信息
                PayOrderCard payOrderCard = customerStationEnterprisedService.selectPayOrderByoOrderNo(customerCardUseRecord1.getOrderNo());
                if (ObjectUtils.isNotEmpty(payOrderCard)){
                    customerCardUseRecord1.setPayableAmount(null != payOrderCard.getReceivableAmt() ? payOrderCard.getReceivableAmt() : null);
                    customerCardUseRecord1.setDiscountSum(getDiscountSum(payOrderCard));
                    customerCardUseRecord1.setOilPirce(payOrderCard.getOilPirce());
                    customerCardUseRecord1.setOrderLiters(payOrderCard.getOrderLiters());
                    if (null != payOrderCard.getOilPersonnelId()){
                        customerCardUseRecord1.setOperator(Integer.valueOf(payOrderCard.getOilPersonnelId()));
                    }
                    customerCardUseRecord1.setPaidAmount(payOrderCard.getAmt());
                }
            }
            ElectronicCardRefundRecord refundRecord = new ElectronicCardRefundRecord();
            QueryWrapper<ElectronicCardRefundRecord> qw = new QueryWrapper<>(refundRecord);
            if (StringUtils.equalsAny(payType1, CardRecordType.WX_RECHARGE.getKey(),CardRecordType.POS_RECHARGE.getKey())) {
                // 设置退款状态
                refundRecord.setRechargeRecordId(customerCardUseRecord1.getId());
                Integer integer = electronicCardRefundRecordMapper.selectCount(qw);
                if (integer>0) {
                    customerCardUseRecord1.setRefundStatus(1);
                }else{
                    customerCardUseRecord1.setRefundStatus(0);
                }
            }

            if(StringUtils.isNotEmpty(payType1)&&
                    (payType1.equals(CustomerCardUseRecord.PAY_TYPE_CONSUME_REF)||
                            payType1.equals(CustomerCardUseRecord.PAY_TYPE_CONSUME_PRESENT)||
                            payType1.equals(CustomerCardUseRecord.PAY_TYPE_CONSUME_PRESENT_REFUND)
                            )
            ){
                //电子卡退款应该没有应付金额 和折扣金额
                customerCardUseRecord1.setPayableAmount(null);
                customerCardUseRecord1.setDiscountSum(null);
            }

            //余额调整操作人名称
            if (null !=customerCardUseRecord1.getOperator()){
                SysUser sysUser1 = sysUserMap.get(customerCardUseRecord1.getOperator());
                if (sysUser1 == null) {
                    sysUser1 = sysUserService.getById(Long.valueOf(customerCardUseRecord1.getOperator()));
                    sysUserMap.put(customerCardUseRecord1.getOperator(),sysUser1);
                }
                if (ObjectUtils.isNotEmpty(sysUser1)){
                    customerCardUseRecord1.setOperatorName(sysUser1.getNickName());
                }
            }

        }
        return recordList;
    }

    private BigDecimal getDiscountSum(PayOrderCard payOrderCard){
        BigDecimal discountSum = BigDecimal.ZERO;
        if (null != payOrderCard.getDiscountAmt()){
            discountSum = discountSum.add(payOrderCard.getDiscountAmt());
        }
        if (null != payOrderCard.getDiscountCouponAmt()){
            discountSum = discountSum.add(payOrderCard.getDiscountCouponAmt());
        }
        return discountSum;
    }
}
